package com.dhcc.android.base.utils.amap;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;

import com.dhcc.android.base.R;
import com.dhcc.android.base.utils.CommenUtil;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechListener;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;

/**
 * 语音播报组件
 */
public class TTSController {

    public static TTSController ttsManager;
    private Context mContext;
    // 语音+安装助手类
    private ApkInstaller mInstaller;
    // 合成对象.
    private SpeechSynthesizer mSpeechSynthesizer;

    public TTSController(Context context) {
        mContext = context;
        init();
    }

    public static TTSController getInstance(Context context) {
        if (ttsManager == null) {
            ttsManager = new TTSController(context);
        }
        return ttsManager;
    }

    public void init() {
        SpeechUtility.createUtility(mContext, "appid=" + mContext.getString(R.string.app_id));
        // 初始化合成对象.
        mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext, mTtsInitListener);
        mInstaller = new ApkInstaller(mContext);
//		mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext);
        initSpeechSynthesizer();
    }

    /**
     * 使用SpeechSynthesizer合成语音，不弹出合成Dialog.
     *
     * @param
     */
    public void playText(String playText) {
        System.out.println("playText:" + playText);
        System.out.println("isFinish:" + isfinish);
        // 进行语音合成.

        if (!isfinish) {
            return;
        }
        if (null == mSpeechSynthesizer) {
            // 创建合成对象.
            mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(mContext, mTtsInitListener);
            initSpeechSynthesizer();
        }

//		/** 
//		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
//		 * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
//		*/
//		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
//		int code = mTts.synthesizeToUri(text, path, mTtsListener);
        int code = mSpeechSynthesizer.startSpeaking(playText, mTtsListener);
        System.out.println("合成码：" + code);
        if (code != ErrorCode.SUCCESS) {
            if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                //未安装则跳转到提示安装页面
                mInstaller.install();
            } else {
                System.out.println("语音合成失败,错误码: " + code);
            }
        }


    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                CommenUtil.toast("初始化失败,错误码：" + code, mContext);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    public void stopSpeaking() {
        if (mSpeechSynthesizer != null)
            mSpeechSynthesizer.stopSpeaking();
    }

    public void startSpeaking() {
        isfinish = true;
    }
//
//	private void initSpeechSynthesizer() {
//		// 设置发音人
//		mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME,"xiaoyan");
//		// 设置语速
//		mSpeechSynthesizer.setParameter(SpeechConstant.SPEED,"tts_speed");
//		// 设置音量
//		mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME,"tts_volume");
//		// 设置语调
//		mSpeechSynthesizer.setParameter(SpeechConstant.PITCH,"tts_pitch");
//
//	}


    /**
     * 参数设置
     *
     * @param param
     * @return
     */
    private void initSpeechSynthesizer() {
        // 清空参数
        mSpeechSynthesizer.setParameter(SpeechConstant.PARAMS, null);
//		// 根据合成引擎设置相应参数
//		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
        mSpeechSynthesizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置在线合成发音人
        mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");
//		}else {
//			mSpeechSynthesizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
//			// 设置本地合成发音人 voicer为空，默认通过语音+界面指定发音人。
//			mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME,"");
//		}
        //设置合成语速
        mSpeechSynthesizer.setParameter(SpeechConstant.SPEED, "50");
        //设置合成音调
        mSpeechSynthesizer.setParameter(SpeechConstant.PITCH, "50");
        //设置合成音量
        mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME, "50");
        //设置播放器音频流类型
        mSpeechSynthesizer.setParameter(SpeechConstant.STREAM_TYPE, "3");

        // 设置播放合成音频打断音乐播放，默认为true
        mSpeechSynthesizer.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置合成音频保存路径，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        mSpeechSynthesizer.setParameter(SpeechConstant.PARAMS, "tts_audio_path=" + Environment.getExternalStorageDirectory() + "/test.pcm");
    }

    /**
     * 用户登录回调监听器.
     */
    private SpeechListener listener = new SpeechListener() {


        @Override
        public void onCompleted(SpeechError error) {
            if (error != null) {

            }
        }

        @Override
        public void onEvent(int arg0, Bundle arg1) {
        }

        @Override
        public void onBufferReceived(byte[] arg0) {
            // TODO Auto-generated method stub

        }
    };
    boolean isfinish = true;
    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {
        @Override
        public void onBufferProgress(int arg0, int arg1, int arg2, String arg3) {
            // TODO Auto-generated method stub
            System.out.println("合成进度：" + arg0);
        }

        @Override
        public void onCompleted(SpeechError arg0) {
            // TODO Auto-generated method stub
            isfinish = true;
            System.out.println("播放完成");
        }

        @Override
        public void onSpeakBegin() {
            // TODO Auto-generated method stub
            System.out.println("开始播放");
            isfinish = false;

        }

        @Override
        public void onSpeakPaused() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSpeakProgress(int arg0, int arg1, int arg2) {
            // TODO Auto-generated method stub
            System.out.println("播放进度：" + arg0);
        }

        @Override
        public void onSpeakResumed() {
            // TODO Auto-generated method stub

        }

        @Override
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
            // TODO Auto-generated method stub
            System.out.println("onEvent");
        }
    };


    public void destroy() {
        if (mSpeechSynthesizer != null) {
            mSpeechSynthesizer.stopSpeaking();
        }
    }


}
